# -*- coding: UTF-8 -*-

import requests
from bs4 import BeautifulSoup

WEBSITE = "https://www.pokemon.cn"
URL = "https://www.pokemon.cn/play/pokedex/"
IMG_PATH = "apps/pokemon/img/"

def SaveImg(url, name):
    with open(name, 'wb')  as f:
        f.write(requests.get(url, timeout=5).content)

    print("Save image:", name)

def GetPokemonInfo(num, sub_num):
    if sub_num == 0:
        url = URL + "{:0>4d}".format(num)
    else:
        url = URL + "%04u_%u" % (num, sub_num)
    print(url)
    req = requests.get(url)
    # print(req)
    # print(req.status_code)
    # html = req.text
    # print(html)
    if req.status_code != 200:
        return -1

    soup = BeautifulSoup(req.text, 'html.parser')
    # print(soup.prettify())

    for tag in soup.find_all('div', class_='contents pokemon-detail-contents'):
        # 获取编号和名称
        pokemon_no = tag.find('p', class_='pokemon-slider__main-no').get_text()
        pokemon_name = tag.find('p', class_='pokemon-slider__main-name').get_text()
        print(pokemon_no, pokemon_name)
        
        # 获取图片并保存
        pokemon_img = tag.find('img', class_='pokemon-img__front')

        img_url = WEBSITE + pokemon_img.get('src')
        # img_name = pokemon_no + '-' + pokemon_name + ".png"
        if sub_num == 0:
            img_name = IMG_PATH + "%04u" % (num)
        else:
            img_name = IMG_PATH + "%04u_%u" % (num, sub_num)

        # print(img_name)
        # print(img_url)

        SaveImg(img_url, img_name + ".png")
        SaveImg(img_url, img_name + '-' + pokemon_name + ".png")

        # 获取属性
        pokemon_type = tag.find_all('div', class_='pokemon-type__type')
        # print(pokemon_type)

        type_list = []
        for type in pokemon_type:
            type_list.append(type.find('span').get_text())
        print("属性：", type_list)

        # 获取弱点
        pokemon_weakness = tag.find_all('div', class_='pokemon-weakness__btn')
        # print(pokemon_weakness)

        weakness_list = []
        for weakness in pokemon_weakness:
            weakness_list.append(weakness.find('span').get_text())
        print("弱点：", weakness_list)
    
    return 0

def main():
    # GetPokemonInfo(1, 0)
    for i in range(152):
        for j in range(5):
            ret = GetPokemonInfo(i, j)
            if ret != 0:
                break;

if __name__ == '__main__':
    main()
